﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ChallengePuzzle.Lib
{
    public delegate void MethodHandle();

    public class Excuter
    {

        List<Thread> tPool = new List<Thread>();

        public void Exc(MethodHandle method)
        {

            Thread t = GetAFreeThread();

            t = new Thread(new ThreadStart(method));

            //Thread t = new Thread(new ThreadStart(method));

            //tPool.Add(t);

            t.Start();
        }

        private Thread GetAFreeThread()
        {
            if (tPool.Count < 2)
            {
                Thread t = new Thread(new ThreadStart(NullMethod));
                tPool.Add(t);
                return t;
            }

            bool HasFreeThread = true;

            while (HasFreeThread)
            {
                foreach (Thread t in tPool)
                {

                    if (t.ThreadState == ThreadState.Stopped) return t;
                    if (t.ThreadState == ThreadState.Aborted) return t;
                    if (t.ThreadState == ThreadState.Unstarted) return t;
                    //if (t.ThreadState == ThreadState.Aborted) return t;
                }
            }

            return null;
        }

        internal void Stop()
        {
            foreach (Thread t in tPool)
            {
                t.Abort();
                //if (t.ThreadState == ThreadState.Running)
                //{
                //    t.Abort();
                //}
            }
        }

        public Excuter()
        {
            //tPool.Add
        }



        private void NullMethod()
        {

        }
    }
}
